#!/usr/bin/python
#!coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
import sys,os
class test:
	def __init__(self):
		self.x_max_diff = 0 #相邻x坐标最大差值
		self.y_max_diff = 0
		self.z_max_diff = 0

		self.minval=[0xffff,0xffff,0xffff] #x,y,z坐标最小值
		self.maxval=[0,0,0]

		self.xvals=[] #所有x坐标集合
		self.yvals=[]
		self.zvals=[]
		self.pdvals=[]

		self.xoldvals=[] #所有为校准x坐标集合
		self.yoldvals=[]
		self.zoldvals=[]

		self.xdiffvals=[] #所有相邻x坐标差值集合
		self.ydiffvals=[]
		self.zdiffvals=[]
	
	def __val_abs_diff(self,newval,oldval):
		if (newval>oldval):
			return newval - oldval
		else:
			return oldval - newval
	def pointdeal(self,lx,ly,lz):
		"""lx,ly,lz 坐标列表"""
		length = len(lx)
		for i in range(0,length-1):
			self.minval[0] = min(lx[i],self.minval[0])
			self.maxval[0] = max(lx[i],self.maxval[0])
			self.xdiffvals.append(abs(lx[i+1]-lx[i]))
			print "----|lx[%d]-lx[%d]|=%d" %(lx[i+1],lx[i],abs(lx[i+1]-lx[i]))

			self.minval[1] = min(ly[i],self.minval[1])
			self.maxval[1] = max(ly[i],self.maxval[1])
			self.ydiffvals.append(abs(ly[i+1]-ly[i]))

			self.minval[2] = min(lz[i],self.minval[2])
			self.maxval[2] = max(lz[i],self.maxval[2])
			self.zdiffvals.append(abs(lz[i+1]-lz[i]))

			if abs(lx[i+1]-lx[i])>=500:
				#lx[i+1] = lx[i]
				#ly[i+1] = ly[i]
				pass
			if abs(ly[i+1]-ly[i])>=500:
				#lx[i+1] = lx[i]
				#ly[i+1] = ly[i]
				pass

	def amp_filter(self,lx,ly,lz):
		length = len(self.xdiffvals)
		for i in range(length-1):
			if (self.xdiffvals[i] >= 500):
				lx[i+1] = lx[i]
			if (self.xdiffvals[i] >= 500):
				ly[i+1] = ly[i]
	def cali_pointer(self,lx,ly,lz,count):
		nlx=[]
		nly=[]
		nlz=[]
		step=count
	#	self.amp_filter(lx,ly,lz)

		for i in range(0,len(lx),step):
			
			lxsorted=sorted(lx[i:i+step])
			nlx.append(sum(lxsorted[1:-1])/(step-2))

			lysorted=sorted(ly[i:i+step])
			nly.append(sum(lysorted[1:-1])/(step-2))

			lzsorted=sorted(lz[i:i+step])
			nlz.append(sum(lzsorted[1:-1])/(step-2))
		return nlx,nly,nlz
if __name__ == "__main__":
	os.system("sed -n '/point/p' points.txt  > point1.txt")
	t = test()
	i = 0
	fd = open("points.txt",'r')
	#fd = open("/home/litte/minicom.cap",'r')
	for line in fd.readlines():
		if line.startswith("#") or line.find('pressure') < 0 or line.startswith('<'):
			continue
		print line,type(line)
		x,y,z,pd = map(int,line.replace('pressure','').replace('point','').replace('pendown','').replace('(','').replace(')','').replace(' ','').strip('\n').split(','))
		#x+=100
		#y+=100
		#z+=100
		t.xoldvals.append(x)
		t.yoldvals.append(y)
		t.zoldvals.append(z)
		t.pdvals.append(pd)
#	t.amp_filter(t.xoldvals,t.yoldvals,t.zoldvals)
	t.pointdeal(t.xoldvals,t.yoldvals,t.zoldvals)
	t.xvals,t.yvals,t.zvals = t.cali_pointer(t.xoldvals,t.yoldvals,t.zoldvals,20)
	#t.xvals,t.yvals,t.zvals = t.xoldvals,t.yoldvals,t.zoldvals

	t.x_max_diff = sorted(t.xdiffvals)[-1]
	t.y_max_diff = sorted(t.ydiffvals)[-1]
	t.z_max_diff = sorted(t.zdiffvals)[-1]
	print "max_diff    :",t.x_max_diff,t.y_max_diff,t.z_max_diff
	print "xyz_min_val :",t.minval
	print "xyz_max_val :",t.maxval
	fd.close()
	#设置画布大小（xmin,xmax,ymin,ymax）
	plt.axis([0, t.maxval[0]+300, 0, t.maxval[1]+300])
	plt.ion()#每个plot都绘制
	plt.subplot(411)
	plt.plot(t.yvals,t.xvals,'b-')
	plt.title('x_y_vals')

	plt.subplot(412)
	plt.title('xy_diff_vals:x-read y-blue')
	plt.plot(t.xdiffvals,'r-')
	plt.grid(True)
	print "xoldvals:",t.xoldvals
	print "xdiffvals:",t.xdiffvals
	plt.plot(t.ydiffvals,'b-')
	plt.grid(True)
	print "yoldvals:",t.yoldvals
	print "ydiffvals:",t.ydiffvals

	plt.subplot(413)
	plt.plot(t.zvals,'b-')
	plt.title('z_vals')
	plt.grid(True)

	plt.subplot(414)
	plt.plot(t.zdiffvals,'r-')
	plt.title('z_diff_vals')
	print "zoldvals:",t.zoldvals
	print "zdiffvals:",t.zdiffvals
	plt.grid(True)

	for i in range(len(t.xvals)):
		#coord ='('+str(i)+': ' + str(t.xvals[i])+','+str(t.yvals[i])+')'
		coord ='('+str(i)+')'
	#	plt.annotate(coord, xy=(t.xvals[i], t.yvals[i]), xytext=(t.xvals[i], t.yvals[i]))
		#plt.annotate(coord, xy=(t.xvals[i], t.yvals[i]), xytext=(t.xvals[i]+200, t.yvals[i]+200), arrowprops=dict(facecolor='black', shrink=0.08))

#	for i in range(0,len(t.xvals)-1):
		#plt.scatter(i, y)
#		plt.pause(0.01)
	plt.show()
	raw_input("enter:")

